<?php

namespace app\admin\controller;

use app\common\controller\Base;
use app\common\service\ProductCat as ProductCatService;
use think\Request;

class ProductCat extends Base{

    public function index(){

        $productCatService = new ProductCatService();
        $tree = $productCatService -> getMenusTree();

        return view('',['tree'=>$tree]);
    }

    public function add(){

        $productCatService = new ProductCatService();
        $tree = $productCatService -> getMenusTree();

        return view('',['tree'=>$tree]);
    }

    public function edit(Request $request){

        $id = $request -> param('id');
        if(empty($id)) $this->error("访问来源错误");

        $productCatService = new ProductCatService();

        $productCat = $productCatService->find($id);

        $tree = $productCatService -> getMenusTree();

        return view('',['productCat'=>$productCat,'tree'=>$tree]);
    }

    public function create(Request $request){
        if(!$request->isPost()){
            $this->error("非法途径访问");
        }
        $data = $request->only(['name','pid']);

        $productCatService= new ProductCatService();

        $result = $productCatService ->insert($data);

        if($result['state']) {
            $this->success("操作成功");
        }else{
            $this->error($result['message']);
        }

    }

    public function update(Request $request){
        if(!$request->isPost()){
            $this->error("非法途径访问");
        }

        $data = $request->only(['id','name']);

        $productCatService= new ProductCatService();

        $result = $productCatService ->update($data);

        if(1 == $result['state']) {
            $this->success("操作成功");
        }else{
            $this->error("操作失败");
        }
    }

    public function delete(Request $request){
        if(!$request->isDelete()){
            $this->error("非法访问途径");
        }
        $id = $request->only(['id']);
        if(count($id) !== 1){
            $this->error("禁止批量操作");
        }
        $productCatService= new ProductCatService();
        $count = $productCatService -> delete($id);

        if($count){
            $this->success("操作成功");
        }else{
            $this->error("操作失败");
        }
    }

}